package com.all.seria.serialize.hessian2;

import com.all.seria.serialize.Serializer;
import com.caucho.hessian.io.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Author LY
 * @create 2024/5/10 16:13
 * @Description Hessian2序列化与反序列化
 * 注意：针对日期类型 LocalDateTime 需要替换为 Date 否则使用 Hessian2 进行序列化会抛异常
 */
public class Hessian2Serializer implements Serializer {

    @Override
    public <T> byte[] serialize(T obj) {
        if (obj == null){
            throw new RuntimeException("serialize object is null");
        }
        byte[] result = new byte[0];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);
        try {
            hessian2Output.startMessage();
            hessian2Output.writeObject(obj);
            hessian2Output.flush();
            hessian2Output.completeMessage();
            result = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }finally {
            try {
                if(hessian2Output != null){
                    hessian2Output.close();
                    byteArrayOutputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        return result;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> cls) {
        if (data == null){
            throw new RuntimeException("deserialize data is null");
        }
        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(data);
        Hessian2Input hessian2Input = new Hessian2Input(byteInputStream);
        T object = null;
        try {
            hessian2Input.startMessage();
            object = (T)hessian2Input.readObject();
            hessian2Input.completeMessage();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }finally {
            try {
                if(null !=hessian2Input){
                    hessian2Input.close();
                    byteInputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            return object;
        }
    }

}
